#!/usr/bin/env node
8
const fs = require('fs')
const http = require('http')
const path = require('path')

// 检查命令行参数的格式
if (process.argv.length !== 3) {
    console.error('命令行参数格式不正确。正确格式: cmd file_name')
    process.exit(1)
}
// 获取命令行参数中的文件名
const fileName = process.argv[2]
// 检查文件是否存在
if (!fs.existsSync(fileName)) {
    console.error(`文件不存在: ${fileName}`)
    process.exit(1)
}

function createDataUrI(fileName) {
    try {
        const data = fs.readFileSync(fileName)
        const ext = path.extname(fileName).substring(1)
        const base64Data = data.toString('base64')
        return `data:image/${ext};base64,${base64Data}`
    } catch (err) {
        console.error('文件读取错误或文件不存在:', err.message)
        process.exit(1)
    }
}
const dataUri = createDataUrI(fileName)
console.log('Data URI:', dataUri)

// 创建 HTML 页面
const html = `
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data URI Example</title>
  </head>
  <body>
    <img src="${dataUri}" alt="Embedded Image">
  </body>
  </html>
`
const server = http.createServer()
server.on('request', (req, res) => {
    res.end(html)
})
server.listen(8080)

